﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace AviJoiner
{
    class Program
    {
        static void Main(string[] args)
        {
            string folder = args[0];
            if (!folder.EndsWith("\""))
                folder += "\\";

            string searchPattern = args[1];


            string[] fileNames = Directory.GetFiles(folder, searchPattern);

            // copy /B “C:\movie1.mpg” + “C:\movie2.mpg” + “C:\movie3.mpg” “C:\completemovie.mpg”

            StringBuilder batchBuilder = new StringBuilder();
            batchBuilder.Append("copy /B");
            for (int i=0; i<fileNames.Length; i++)
            {   
                batchBuilder.AppendFormat(" \"{0}\" ", fileNames[i]);
                if (i != fileNames.Length - 1)
                    batchBuilder.Append(" + ");
            }

            string outputMovieFileName = fileNames[0].Substring(0, fileNames[0].LastIndexOf('.')) + "_Joined" +
                fileNames[0].Substring(fileNames[0].LastIndexOf('.'), 4);
            batchBuilder.AppendFormat(" \"{0}\"", outputMovieFileName);

            string outputBatchFileName = fileNames[0].Substring(0, fileNames[0].LastIndexOf('.')) + "_Joined.bat";
            
            using (StreamWriter writer = new StreamWriter(outputBatchFileName))
            {
                writer.Write(batchBuilder.ToString());
                writer.Flush();
            }

            //Create a new process info structure.
            ProcessStartInfo pInfo = new ProcessStartInfo();
            //Set the file name member of the process info structure.
            pInfo.FileName = outputBatchFileName;
            //Start the process.
            Process p = Process.Start(pInfo);
            //Wait for the window to finish loading.
//            p.WaitForInputIdle();
            //Wait for the process to end.
            p.WaitForExit();

            foreach (string file in fileNames)
            {
                File.Delete(file);
            }
            File.Delete(outputBatchFileName);
				
        }
    }
}
